/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xuly;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import tuyensinh.BangDiem;
import tuyensinh.DoiTuong;
import tuyensinh.KhuVuc;
import tuyensinh.ThiSinh;
import tuyensinh.Users;

/**
 *
 * @author user
 */
public class XuLy extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            String yeucau = request.getParameter("yc");
            if (yeucau.equals("admin_login")) {
                login(request, response);
            } else if (yeucau.equals("admin_themdiem")) {
                insertThiSinh(request, response);
            } else if (yeucau.equals("admin_suadiem_sbd")) {
                timBangDiemBySbd(request, response);
            } else if (yeucau.equals("admin_suadiem_diem")) {
                updateDiem(request, response);
            } else if (yeucau.equals("admin_suatsinfo_sbd")) {
                timThiSinhBySbd(request, response);
            } else if (yeucau.equals("admin_suatsinfo_info")) {
                updateTsInfo(request, response);
            } else if (yeucau.equals("thisinh_xemdiem")) {
                xemdiem(request, response);
            } else if (yeucau.equals("thisinh_xemxephang")) {
                xemXepHang(request, response);
            } else if (yeucau.equals("admin_logout")) {
                logout(request, response);
            }
        } catch (IOException | SQLException | ServletException ex) {
            Logger.getLogger(XuLy.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Users admin = Users.login(username, password);
        if (admin == null) {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_login.jsp");
            dispatcher.forward(request, response);
        } else {
            request.getSession().setAttribute("admin", admin);
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_welcome.jsp");
            dispatcher.forward(request, response);
        }
    }

    private void insertThiSinh(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
        Users admin = (Users) request.getSession().getAttribute("admin");
        if (admin == null) {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_login.jsp");
            dispatcher.forward(request, response);
            return;
        }
        String sbd = request.getParameter("sbd");
        String hoten = request.getParameter("hoten");
        String ngaysinh = request.getParameter("ngaysinh");
        String manganh = request.getParameter("manganh");
        String makhuvuc = request.getParameter("makhuvuc");
        String madoituong = request.getParameter("madoituong");
        String sdiemmon1 = request.getParameter("diemmon1");
        String sdiemmon2 = request.getParameter("diemmon2");
        String sdiemmon3 = request.getParameter("diemmon3");

        if (sbd.trim().equals("") || hoten.trim().equals("") || ngaysinh.trim().equals("")
                || manganh.trim().equals("") || makhuvuc.trim().equals("") || madoituong.trim().equals("")
                || sdiemmon1.trim().equals("") || sdiemmon2.trim().equals("") || sdiemmon3.trim().equals("")) {
            request.setAttribute("tb", "**Ban phai nhap day du cac field");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_nhapdiem.jsp");
            dispatcher.forward(request, response);
            return;
        }

        ThiSinh ts = new ThiSinh(sbd, hoten, ngaysinh, manganh, makhuvuc, madoituong);
        float diemmon1 = 0f, diemmon2 = 0f, diemmon3 = 0f;
        try {
            diemmon1 = Float.parseFloat(sdiemmon1);
            diemmon2 = Float.parseFloat(sdiemmon2);
            diemmon3 = Float.parseFloat(sdiemmon3);
            if (diemmon1 < 0 || diemmon1 > 10 || diemmon2 < 0 || diemmon2 > 10 || diemmon3 < 0 || diemmon3 > 10) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException ex) {
            request.setAttribute("tb", "**Diem nhap vao khong hop le!");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_nhapdiem.jsp");
            dispatcher.forward(request, response);
            return;
        }

        float tongdiem = KhuVuc.getDiemCongByMaKV(makhuvuc) + DoiTuong.getDiemCongByMaDT(madoituong) + diemmon1 + diemmon2 + diemmon3;
        BangDiem bd = new BangDiem(sbd, manganh, diemmon1, diemmon2, diemmon3, tongdiem);
        ts.insThiSinh();
        bd.insBangDiem();
        request.setAttribute("tb", "<b style=\"color: blue\">**Nhap thanh cong </b>");
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_nhapdiem.jsp");
        dispatcher.forward(request, response);
        return;
    }

    private void timBangDiemBySbd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        Users admin = (Users) request.getSession().getAttribute("admin");
        if (admin == null) {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_login.jsp");
            dispatcher.forward(request, response);
            return;
        }
        String sbd = request.getParameter("sbd");
        if (sbd.trim().equals("")) {
            request.setAttribute("tb", "<b style=\"color: red\">**So bao danh khong hop le </b>");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_suadiem.jsp");
            dispatcher.forward(request, response);
            return;
        }
        BangDiem bd = BangDiem.findBangDiemBySbd(sbd);
        if (bd == null) {
            request.setAttribute("tb", "<b style=\"color: red\">**So bao danh khong dung </b>");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_suadiem.jsp");
            dispatcher.forward(request, response);
            return;
        }

        request.getSession().setAttribute("bangdiem", bd);
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_suadiem.jsp");
        dispatcher.forward(request, response);
    }

    private void updateDiem(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        Users admin = (Users) request.getSession().getAttribute("admin");
        if (admin == null) {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_login.jsp");
            dispatcher.forward(request, response);
            return;
        }
        String sdiemmon1 = request.getParameter("diemmon1");
        String sdiemmon2 = request.getParameter("diemmon2");
        String sdiemmon3 = request.getParameter("diemmon3");
        String sbd = request.getParameter("sbd");
        if (sdiemmon1.trim().equals("") || sdiemmon2.trim().equals("") || sdiemmon3.trim().equals("")) {
            request.setAttribute("tb", "<b style=\"color: blue\">**Diem khong hop le </b>");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_suadiem.jsp");
            dispatcher.forward(request, response);
            return;
        }
        float diemmon1 = 0f, diemmon2 = 0f, diemmon3 = 0f;
        try {
            diemmon1 = Float.parseFloat(sdiemmon1);
            diemmon2 = Float.parseFloat(sdiemmon2);
            diemmon3 = Float.parseFloat(sdiemmon3);
            if (diemmon1 < 0 || diemmon1 > 10 || diemmon2 < 0 || diemmon2 > 10 || diemmon3 < 0 || diemmon3 > 10) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException ex) {
            request.setAttribute("tb", "**Diem khong hop le!");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_suadiem.jsp");
            dispatcher.forward(request, response);
            return;
        }
        BangDiem.updateDiem(sbd, diemmon1, diemmon2, diemmon3);
        request.getSession().setAttribute("bangdiem", null);
        request.setAttribute("tb", "<b style=\"color: blue\">**Sua diem thanh cong </b>");
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_suadiem.jsp");
        dispatcher.forward(request, response);
    }

    private void timThiSinhBySbd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        Users admin = (Users) request.getSession().getAttribute("admin");
        if (admin == null) {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_login.jsp");
            dispatcher.forward(request, response);
            return;
        }
        String sbd = request.getParameter("sbd");
        if (sbd.trim().equals("")) {
            request.setAttribute("tb", "<b style=\"color: red\">**So bao danh khong hop le </b>");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_suathongtints.jsp");
            dispatcher.forward(request, response);
            return;
        }
        ThiSinh ts = ThiSinh.findThiSinhBySbd(sbd);
        if (ts == null) {
            request.setAttribute("tb", "<b style=\"color: red\">**So bao danh khong dung </b>");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_suathongtints.jsp");
            dispatcher.forward(request, response);
            return;
        }

        request.getSession().setAttribute("thisinh", ts);
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_suathongtints.jsp");
        dispatcher.forward(request, response);
    }

    private void updateTsInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        Users admin = (Users) request.getSession().getAttribute("admin");
        if (admin == null) {
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_login.jsp");
            dispatcher.forward(request, response);
            return;
        }
        String sbd = request.getParameter("sbd");
        String hoten = request.getParameter("hoten");
        String ngaysinh = request.getParameter("ngaysinh");
        String manganh = request.getParameter("manganh");
        String makhuvuc = request.getParameter("makhuvuc");
        String madoituong = request.getParameter("madoituong");

        if (sbd.trim().equals("") || hoten.trim().equals("") || ngaysinh.trim().equals("")
                || manganh.trim().equals("") || makhuvuc.trim().equals("") || madoituong.trim().equals("")) {
            request.setAttribute("tb", "<b style=\"color: red\">**Ban phai nhap day du cac field </b>");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_suathongtints.jsp");
            dispatcher.forward(request, response);
            return;
        }
        ArrayList<String> listMaKhuVuc = KhuVuc.getDsMaKhuVuc();
        if (!listMaKhuVuc.contains(makhuvuc)) {
            request.setAttribute("tb", "<b style=\"color: red\">**Ma khu vuc khong ton tai </b>");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_suathongtints.jsp");
            dispatcher.forward(request, response);
            return;
        }

        ArrayList<String> listMaDoiTuong = DoiTuong.getDsMaDoiTuong();
        if (!listMaDoiTuong.contains(madoituong)) {
            request.setAttribute("tb", "<b style=\"color: red\">**Ma doi tuong khong ton tai </b>");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_suathongtints.jsp");
            dispatcher.forward(request, response);
            return;
        }
        ThiSinh.updateThiSinhInfo(sbd, hoten, ngaysinh, manganh, makhuvuc, madoituong);
        request.getSession().setAttribute("thisinh", null);
        request.setAttribute("tb", "<b style=\"color: blue\">**Sua thong tin thi sinh thanh cong </b>");
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_suathongtints.jsp");
        dispatcher.forward(request, response);
    }

    private void xemdiem(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String luachon = request.getParameter("luachon");
        String keyword = request.getParameter("keyword").trim();
        if (keyword.trim().equals("")) {
            request.setAttribute("tb", "Ban phai nhap ten/ so bao danh hop le");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/thisinh_xemdiem_sbd.jsp");
            dispatcher.forward(request, response);
            return;
        }
        if (luachon.equals("theoten")) {
            ArrayList<ThiSinh> listThiSinh = ThiSinh.findThiSinhByTen(keyword);
            String result = "";
            if (listThiSinh.isEmpty()) {
                result = "<tr><td colspan=\"7\" style=\"text-align: center\"> Khong tim thay ket qua </td></tr>";
            } else {
                for (ThiSinh ts : listThiSinh) {
                    BangDiem bd = BangDiem.findBangDiemBySbd(ts.getSbd());
                    result += "<tr><td>" + ts.getSbd() + "</td><td>" + ts.getHoten() + "</td><td>"
                            + ts.getNgaysinh() + "</td><td>" + bd.getDiemmon1() + "</td><td>" + bd.getDiemmon2()
                            + "</td><td>" + bd.getDiemmon3() + "</td><td>" + bd.getTongdiem() + "</td></tr>";
                }
            }
            request.getSession().setAttribute("ketqua", result);
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/thisinh_xemdiem_diem.jsp");
            dispatcher.forward(request, response);
        } else if (luachon.equals("theosbd")) {
            ThiSinh ts = ThiSinh.findThiSinhBySbd(keyword);
            if (ts == null) {
                request.setAttribute("tb", "So bao danh khong ton tai");
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/thisinh_xemdiem_sbd.jsp");
                dispatcher.forward(request, response);
                return;
            }
            BangDiem bd = BangDiem.findBangDiemBySbd(keyword);
            String result = "<tr><td>" + ts.getSbd() + "</td><td>" + ts.getHoten() + "</td><td>"
                    + ts.getNgaysinh() + "</td><td>" + bd.getDiemmon1() + "</td><td>" + bd.getDiemmon2()
                    + "</td><td>" + bd.getDiemmon3() + "</td><td>" + bd.getTongdiem() + "</td></tr>";
            request.getSession().setAttribute("ketqua", result);
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/thisinh_xemdiem_diem.jsp");
            dispatcher.forward(request, response);
        }
    }

    private void xemXepHang(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String sbd = request.getParameter("sbd");
        if (sbd.trim().equals("")) {
            request.setAttribute("tb", "<b style=\"color: red\">**So bao danh khong hop le </b>");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/thisinh_xemxephang.jsp");
            dispatcher.forward(request, response);
            return;
        }
        ThiSinh ts = ThiSinh.findThiSinhBySbd(sbd);
        if (ts == null) {
            request.setAttribute("tb", "<b style=\"color: red\">**So bao danh khong dung </b>");
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/thisinh_xemxephang.jsp");
            dispatcher.forward(request, response);
            return;
        }
        String ketqua = BangDiem.getXepHang(sbd);
        request.setAttribute("thisinh", ts);
        request.setAttribute("ketqua", ketqua);
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/thisinh_xemxephang.jsp");
        dispatcher.forward(request, response);
    }

    private void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();

        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin_login.jsp");
        dispatcher.forward(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
